<template>  
  <div class="music-page">  
    <!-- 上半部分 -->  
    <div class="top-half">  
      <!-- 左侧：图片和歌曲信息 -->  
      <div class="left-part"> 
        <div class="album-container">
          <el-card>
              <div class="card-content">
                <div class="top-part">
                  <div class="left-side">
                    <img :src="'http://localhost:8080/images/upload/' + music.cover_image" alt="Album Cover" class="album-image" />
                  </div>
                  <div class="right-side">
                    <h2 class="song-title">{{ '歌曲 : '+music.music_name }}</h2>
                    <p>歌手：{{ music.artist }}</p>
                    <p>类型：{{ music.type }}</p>
                  </div>
                </div>
                <div class="bottom-part">
                  <textarea class="song-textarea" readonly>{{ '歌曲简介:' + music.description }}</textarea>
                </div>
              </div>
          </el-card>
        <br>
        
            <!-- <div class="song-info">  
            <h1 class="song-title">{{ music.music_name }}</h1>  
            <p>歌手：{{ music.artist }}</p>  
            <p>类型：{{ music.type }}</p>  
        </div>  -->
      </div> 
        <!-- 词云区域 -->  
        <div>  
         
          <div id="wordCloud" style="width: 500px; height: 400px;"></div>  
        </div>  
      </div>  

      <!-- 右侧：按钮和评论 -->  
      <div class="right-part">  
        <div class="function-buttons" style="margin-bottom: 20px;">  
          <!-- <audio ref="audioPlayer" controls>  
            <source :src="'http://localhost:8080/images/upload/' + currentAudio" type="audio/mpeg" />  
            您的浏览器不支持音频播放。  
          </audio>   -->
          <!-- <el-button type="text" round @click="playMusic(music.audio, music.music_id)">播放</el-button>   -->
          <el-button type="text" icon="Back" @click="$router.go(-1)" style="color: black;"></el-button>  
          <button class="el-button el-button--text el-button--round" @click="generateWordCloud()">查看词云</button>  
        </div>  

        <div class="add-comment">  
          <el-input 
            v-model="newComment" 
            maxlength="50" 
            show-word-limit  
            placeholder="期待你的评论！" 
            clearable 
            class="custom-input" 
          ></el-input>&nbsp;&nbsp;
          <button class="el-button el-button--text el-button--round" @click="submitComment">发送</button>  
        </div>  

        <div class="comments-container">  
          <div v-for="comment in tableData1" :key="comment.id" class="comment">  
            <div class="comment-info">  
              <div class="comment-header">  
                <el-avatar :src="'http://localhost:8080/images/upload/' + comment.profile_picture" class="comment-avatar" @click="opendetail(comment)"></el-avatar>  
                <div class="comment-details">  
                  <span class="comment-author">{{ comment.user_name }}</span>  
                  <div class="comment-date">{{ formatDate(comment.create_time) }}</div>  
                </div>  
              </div>  
              <div class="comment-text">{{ comment.content }}</div>  
            </div>  
            <div class="note-action">  
                <el-button   
                  icon="Star"   
                  plain   
                  round   
                  @click="handleLike(comment)"   
                  style="font-size: 16px; padding: 10px 20px; min-width: 120px;"  
                >  
                  {{ comment.isLiked ? "已点赞" : "点赞" }}&nbsp;({{ comment.likeCount }})  
                </el-button>  
                <el-button   
                  icon="Warning"   
                  plain   
                  round   
                  @click="handleReport(comment.music_comment_id)"   
                  style="font-size: 16px; padding: 10px 20px; min-width: 120px;"  
                >  
                  举报  
                </el-button>  
              </div> 
          </div>  
        </div>  
      </div>  
    </div>  
  </div>  
</template>


<script>  
import WordCloud from 'wordcloud';
import { ElCard, ElMessage, ElMessageBox } from 'element-plus';  
import axios from 'axios';  
export default {  
  data() {  
    return {  
      // 歌曲数据对象  
      music: {  
        cover_image: '',  
        music_name: '',  
        artist: '',  
        type: '',  
        play_count: 0,  
        description: '',
      },  

      tableData: [], // 存储用户头像和用户名  
      tableData1: [],  
      newComment: '',  
      userId:'',  
      music_id:'',  
      publishedCommentCount: 0, // 初始化歌曲评论数量  
      publishedMusicCount: 0,   // 初始化收藏数量  
      commentsText: '',  
      
      musics:[],
      pageInfo: null,
      
  

 
    };  
  },  
  
  methods: {  
    async loadData() {  
  try {  
    // 获取音乐ID  
    this.music_id = sessionStorage.getItem('music_id');  
    console.log(this.music_id);  

    // 获取歌曲信息  
    await this.fetchSongs();  
    this.userId = localStorage.getItem('user_id');  
    
    // 获取评论数据  
    await this.getMusicComment();  
    
    // 生成词云  
    this.generateWordCloud();  
    
    // 检查点赞状态  
    this.checkIfCollected();   
  } catch (error) {  
    console.error('加载数据时出错:', error);  
    ElMessage.error('数据加载失败，请稍后重试。'); // 友好的错误提示  
  }  
}, 
    formatDate(dateString) {  //时间
      const date = new Date(dateString);  
      const year = date.getFullYear();  
      const month = String(date.getMonth() + 1      ).padStart(2, '0');  
      const day = String(date.getDate()).padStart(2, '0');  
      const hours = String(date.getHours()).padStart(2, '0');  
      const minutes = String(date.getMinutes()).padStart(2, '0');  
      return `${year}-${month}-${day} ${hours}:${minutes}`;  
    },  

    //从评论页进入到他人主页
    opendetail(comment) {  
        localStorage.setItem('user_id', this.userId);  
        this.navigateTo(`/HisHome/${comment.user_id}`);  // 使用 `user_id` 来构建路由  
      },   
    navigateTo(route) {  
      this.$router.push(route);  
    },  

//  //获取评论数量
//  fetchpublishedCommentCount() {  
//       axios.get(`/v1/NoteComment/count`, {  
//         params: { note_create_id: this.note_create_id }  
//       }).then(response => {  
//         this.publishedCommentCount = response.data;  
//       });  
//     },  


//  //获取歌曲的收藏数量
//  fetchpublishedNoteCount() {  
//       axios.get(`/v1/NoteCollectionnoteid/count`, {  
//         params: { note_create_id: this.note_create_id }  
//       }).then(response => {  
//         this.publishedNoteCount = response.data;  
//       });  
//     },  

    



    //获取每条评论的点赞数量
    fetchpublishedlikeCount(comment){      //获取每条评论的点赞数量
      axios.get(`http://localhost:8080/likeMusicComment/count`, {  
        params: { music_comment_id: comment.music_comment_id }  
      }).then(response => {  
        comment.likeCount = response.data;  
      }); 
    },

    // 检查是否已经点赞 forEach遍历tableData1数组中的每个评论
    checkIfCollected() {
   this.tableData1.forEach(comment => {
    axios.get(`http://localhost:8080/likeMusicComment/check`, {
        params: { user_id:this.userId, music_comment_id: comment.music_comment_id },
      })
      .then((response) => {
        comment.isLiked = response.data.like; // 设置每个评论的点赞状态
      })
      .catch((error) => {
        console.error("检查点赞状态失败：", error);
      });
  });
},
    
    //获取评论内容
    getMusicComment() {  
      axios.get(`http://localhost:8080/v1/MusicCommentinfonoteid`, {  
        params: { music_id: this.music_id }  
      }).then((response) => {         
        this.tableData1 = response.data.list.map(comment => ({
        ...comment,
        isLiked: false, // 初始化点赞状态   //在不修改原始对象：评论comment的情况下，创建一个新对象isLiked并添加或修改属性。
        likeCount:0     //初始化点赞数量
      }));  
      this.tableData1.forEach(comment => {   // 遍历评论，获取每条评论的点赞数量
        this.fetchpublishedlikeCount(comment);
        
      });
       this.checkIfCollected(); // 初始化时检查点赞状态 
       this.generateWordCloud()
      });   
    }, 

    //生成词云图
    generateWordCloud() {
    // 文本清洗函数
    const cleanText = (text) => {
        const stopWords = ['的', '了', '是', '在', '和', '有', '就', '不','啊']; // 定义停用词
        return text
            .replace(/[，。！？；]/g, '') // 去除中文标点
            .replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g, ' ') // 去除非字母及数字，保留中文字符
            .split(' ') // 按空格分割词语
            .filter(word => word && !stopWords.includes(word)) // 过滤停用词和空白
            .join(' '); // 重新合并
    };

    // 获取清洗后的文本数据
    const textData = this.tableData1.map(comment => cleanText(comment.content)).join(' ');

    const words = textData.split(/\s+/);
    const wordCount = {};

    words.forEach(word => {
        word = word.toLowerCase();
        if (wordCount[word]) {
            wordCount[word] += 1;
        } else {
            wordCount[word] = 1;
        }
    });

    const wordArray = Object.keys(wordCount).map(word => {
        return [word, wordCount[word]];
    });

    WordCloud(document.getElementById('wordCloud'), {
        list: wordArray,
        gridSize: 16, // 缩小单词间距，默认64
        weightFactor: 10, // 单词大小因子，可以根据需要调整
        color: 'random-dark', // 随机深色
        backgroundColor: '#fff', // 背景颜色
        rotate: 0, // 允许旋转（0: 不旋转, 45: 旋转45度, 90: 旋转90度等）
        fontFamily: 'Arial, Helvetica, sans-serif', // 设置字体
        shape: 'circle' // 设置词云形状
    });
},













     //举报 已经实现
     handleReport(music_comment_id) {
      console.log("Reporting comment with ID:", music_comment_id);
    ElMessageBox.confirm(
    '您确定要举报本条评论吗?',
    '举报评论',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      console.log(music_comment_id)
    axios.put(`/v1/MusicCommentStatus/${music_comment_id}`)  //修改状态（被举报）
      .then(response => {
        ElMessage.success('您的举报已收到，谢谢！');
        this.getMusicComment();
      })
      .catch(error => {
        if (axios.isCancel(error)) {
          console.log('Request canceled', error.message);
        } else {
          ElMessage.error('举报失败：' + error.message);
          console.error(error);
        }
      });
    }).catch(() => {
    // 处理用户取消逻辑
       ElMessage.info('举报已取消');
     });
    },







  // 点赞或取消点赞操作
  handleLike(comment) {
  const url = comment.isLiked ? `/likeMusicComment/delete` : `/likeMusicComment/add`;
  const data = { user_id:this.userId, music_comment_id: comment.music_comment_id };
  axios({
    method: comment.isLiked ? "delete" : "post", 
    url,
    data,
  })
  .then((response) => {
    if (response.data.success) {
      comment.isLiked = !comment.isLiked; // 切换单个评论的点赞状态
      this.fetchpublishedlikeCount(comment); // 重新获取点赞数量
      const message = comment.isLiked ? "点赞成功" : "取消点赞成功";
      ElMessage.success(message);
    } else {
      ElMessage.error("操作失败，请稍后再试！");
    }
  })
  .catch((error) => {
    console.error("点赞操作失败：", error);
    ElMessage.error("网络错误，请稍后重试！");
  });
},



    //发送评论
    submitComment() {  
  if (this.newComment.trim() !== '') {  
  
    const commentData = {
      music_id: this.music_id,
      user_id: this.userId,
      content: this.newComment,
      like_count: 0,
      comment_count: 0,
      status: "正常"
    };

    axios.post(`http://localhost:8080/v1/MusicComment`, commentData)  
      .then(() => {  
        this.newComment = ''; // 清空输入框  
        ElMessage.success('评论成功！');  
        this.getMusicComment();  
      })  
      .catch(error => {  
        ElMessage.error('评论失败，请重试！');  
        console.error(error);  
      });  
  }  
},





    fetchSongs() {  //获取当前歌曲信息
      fetch(`http://localhost:8080/music/g1/${this.music_id}`)   
        .then(response => {  
          if (!response.ok) {  
            throw new Error('Network response was not ok');  
          }  
          console.log("here ok")
          return response.json();  
        })  
        .then(data => {  
          this.music = data;  
          console.log(this.music);  
   
        })  
        .catch(error => console.error('Error fetching songs:', error));  
    },  

    
    // 播放歌曲的方法
    playMusic(audio, music_id) {
    this.currentAudio = audio; // 设置当前要播放的音频链接
    console.log("当前音频源:", this.currentAudio); // 打印音频源
    this.$nextTick(() => {
        const audioPlayer = this.$refs.audioPlayer;
        if (audioPlayer) {
          audioPlayer.src = `http://localhost:8080/images/upload/${this.currentAudio}`;
            audioPlayer.load(); // 加载新的音频
            audioPlayer.play().then(() => {
                console.log("播放成功");
            }).catch(error => {
                console.error('播放失败:', error);
            });
           
            this.incrementPlayCount(music_id); // 增加播放次数
        } else {
            console.error("音频播放器引用未定义。");
        }
    });
},
    incrementPlayCount(music_id) {
      // 发送请求到后端，更新播放次数
      this.$http.post('/music/incrementPlayCount', { music_id }).then(response => {
        // 处理响应
        this.fetchSongs(music_id); // 重新获取页面数据以更新播放次数
        this.fetchMusics(music_id); // 重新获取页面数据以更新播放次数
      }).catch(error => {
        console.error('更新播放次数失败', error);
      });
    },
    
  }, 
  mounted() {  
  this.loadData();  // 调用数据加载函数  
}, 
};  
</script>  

<style scoped>
.music-page {
  display: flex;
  flex-direction: column;
}

.top-half {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.left-part {
  flex: 3;
  padding: 20px;
}

.right-part {
  flex: 7;
  padding: 20px;
}

.album-image {
  width: 100%;
  height: auto;
  margin-bottom: 20px;
  border-radius: 10px;
}

.song-info {
  margin-bottom: 20px;
}

.tag {
  color: gray;
  margin-top: 10px;
}

.function-buttons {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 20px;
}

.add-comment {
  display: flex;
  align-items: center;
  margin-top: 10px;
}

.add-comment input {
  width: 80%;
  padding: 10px;
  margin-right: 10px;
}

.comments-container {
  margin-top: 60px;
  overflow-y: auto;
  max-height: 600px;
  border: 1px solid #ddd;
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 4px;
}

.comment {
  display: flex;
  border-bottom: 2px solid #eaeaea;
  align-items: flex-start;
  margin-bottom: 15px;
}

.comment-avatar {
  border-radius: 60%;
  width: 40px;
  height: 40px;
  margin-right: 10px;
}

.comment-info {
  margin-left: 10px;
  flex: 1;
}

.comment-header {
  display: flex;
  align-items: center;
  width: 200px;
}

.comment-details {
  margin-left: 4px;
}

.comment-author {
  font-weight: bold;
}

.comment-date {
  font-size: 12px;
  color: gray;
  margin-top: 5px;
}

.comment-text {
  word-wrap: break-word;
  white-space: normal;
  max-width: 50ch;  
  /* 限定评论字数 */
  text-align: left;
  margin-top: 15px;
  margin-bottom: 15px;
}

.note-action {
  margin-left: auto;
  display: flex;
  align-items: center;
}


.el-button {
  width: 80px;
  background-color: #f9f4e8;
  color: #4b3f33;
}

.el-button:hover {
  background-color: #e0dcd0;
}
</style> 

<!-- 卡片样式 -->
<style>   
.card-content {
  display: flex;
  flex-direction: column; /* 使上下两部分垂直排列 */
}

.top-part {
  display: flex; /* 使用flex布局 */
  justify-content: space-between; /* 左右两侧间隔均匀分布 */
  align-items: center; /* 垂直居中 */
}

.left-side {
  flex: 2; /* 图片区域占据剩余空间 */
}

.right-side {
  flex: 2; /* 歌手和类型信息占据剩余空间 */
  padding-left: 100px; /* 左右间距 */
}

.bottom-part {
  margin-top: 20px; /* 与上部分间隔 */
}
</style>

<style>
.song-textarea {
  width: 80%; /* 文本框宽度 */
  height: 100px; /* 文本框高度 */
  padding: 10px; /* 文本框内边距 */
  border: 1px solid #ccc; /* 文本框边框 */
  border-radius: 4px; /* 文本框圆角 */
  font-size: 16px; /* 字体大小 */
  line-height: 1.5; /* 行高 */
  color: #333; /* 字体颜色 */
  background-color: #f9f9f9; /* 背景颜色 */
  overflow: auto; /* 滚动条 */
  white-space: pre-wrap; /* 保持空格，自动换行 */
  resize: none; /* 禁止调整大小 */
  scrollbar-width: none; /* Firefox隐藏滚动条 */
  -ms-overflow-style: none; /* IE 10+ 隐藏滚动条 */
  outline: none; /* 去掉焦点时的外框 */
}

.song-textarea::-webkit-scrollbar {
  display: none; /* Chrome, Safari 和 Opera 隐藏滚动条 */
}
</style>